"""
Get the performance metric of process, and the network metric
"""
import os,sys,time,threading,string,thread,traceback
from threading import Timer
from Configuration import Configuration
import Analysis
#import psutil #psutill can not be executed in win64
Configuration = Configuration()

class Performance(threading.Thread):
    networkFileName = ""
    running = False
    def __init__(self):
#        if sys.platform == "win32":
#            import psutil
        threading.Thread.__init__(self)
        self.flag = 1
        self.running = False;
        self.resultFile = open("t", "w")
        self.resultFile.close()
    def initVal(self, expId, expName, factor):
        self.expId = expId
        self.expName = expName
        self.factor = factor
        self.flag = 1
        
    def run(self):
#        global Configuration
#        if self.__class__.running == True:
#            print "running yet return"
#            return
#        else :
#            self.__class__.running = True
        Configuration.saveCPUandNetworkFile();
        path = Configuration.getPath()
        hostname = Analysis.getHostname()
        filename = Configuration.getCPUMEMFileName(self.expId, self.expName, self.factor)
#        portFileName = Configuration.getPortFileName(self.expId, self.expName, self.factor)
#        self.portFile = open(portFileName, "w")
        self.resultFile = open(filename,"w")
#        self.cpuFile2 = open(filename2, "a")
#        filename = "packet" + "_" + time.asctime()
#        filename = filename.replace(" ", "_").replace(":", "_")
        filename = Configuration.getPackageName(self.expId, self.expName, self.factor)
        self.networkFileName =filename
        print "measureCPUandMem ..."
        measureNetwork(filename)
        preCpuTime = 0; preElaspedTime= 0
        while(self.flag == 1):
#            if sys.platform == "win32":
#                measureCPUandMemWin32(self.resultFile)
#            else:
                ret = measureCPUandMem(self.resultFile, preCpuTime, preElaspedTime)
                time.sleep(0.4)
                if(ret == None):
                    break;
                preCpuTime = ret[2];preElaspedTime = ret[3]
#            try:
#                measureCPUandMemWin32(self.resultFile)
#                measurePort(self.portFile)
#            except psutil.NoSuchProcess:
#                self.resultFile.flush()
#                self.portFile.flush()
        if(self.flag !=0):
            self.resultFile.flush()
        print "The performance thread exited"
#        self.portFile.flush()
    
    def save(self):
        try:
#            print "saving current file"
            self.resultFile.flush()
            self.flag = 0;
            print "The performance thread is exiting"
#            sys.exit(0);
#            quit();
    #        self.portFile.flush()
#            print "saved"
        except Exception, e:
            exstr   =   traceback.format_exc()
            print   exstr 
            return True;


def measureCPUandMemWin32(resultFile):
    return ;
#    try:
#        ret = psutilMeasure()
#        print >> resultFile, "-----------" + time.asctime() + "\n" + "%f"%time.time()
#        print >> resultFile, ret[0], ret[1], ret[2], ret[3]
#        print >> resultFile, "-----------\n"
#    except psutil.NoSuchProcess:
#        pass
    
def measurePort(file):
    if sys.platform != "win32":
            connections = getProcess().get_connections()
            print >> file, "-----------" + time.asctime() + "\n" + "%f"%time.time()
            print >>file, len(connections)
            for c in connections:
                print >> file, c
            print >> file, "-----------\n"

def measureCPUandMem(resultFile, preCpuTime, preElaspedTime):
    print >> resultFile, "-----------" + time.asctime() + "\n" + "%f"%time.time()
    ret = (0,0,0,0)
    if sys.platform == "win32":
        ret = pslist(preCpuTime, preElaspedTime)
        if(ret==None):
            return ;
        preCpuTime = ret[2]
        preElaspedTime = ret[3]
        print >> resultFile, "win32", ret[0], ret[1]
#        print "win32", ret[0], ret[1]
    elif sys.platform.find("linux") >=0:
        file = os.popen("ps aux|grep openttd")
        lines = file.readlines()
        for line in lines:
            if line.find("openttd") >=0 and line.find("grep openttd")<0:
                print >> resultFile, line
    print >> resultFile, "-----------\n"
#    resultFile.flush()
    return ret

preVM = 0.0
preCpuTime = 0.0
preElaspedTime = 0.0

def getProcess():
    return 
#    for p in psutil.get_process_list():
#        try:
#            if p.name.find("openttd") >= 0:
#                return p
#        except psutil.NoSuchProcess:
#            pass
#    return psutil.Process(0)

def psutilMeasure():
    p = getProcess()
    return (p.get_cpu_percent(interval = 0.4), p.get_memory_info()[1], p.get_cpu_times()[0], p.get_cpu_times()[1])

def pslist(preCpuTime, preElaspedTime):
    if sys.platform == "win32":
        f1 = os.popen("pslist -m openttd")
        lines = f1.readlines()
        i = 0 
        found = False
        for line in lines:
#            print line
            if line.find("openttd") >=0 and line.find("not found") < 0:
                found = True
                break
            i = i + 1
        if found == False:
            return (0,0,0,0)
#        print string.split(lines[3])[2]

        curVM = string.atof(string.split(lines[i])[2])
        f2 = os.popen("pslist openttd")
        lines = f2.readlines()
        words = string.split(lines[i])
        if(len(words)>=8):
            scputime = words[6]
            selaspedtime = words[7]
    #        print scputime, selaspedtime
            t = string.split(scputime,":")
            cputime = string.atof(t[0]) * 3600 + string.atof(t[1]) * 60 + string.atof(t[2])
            t = string.split(selaspedtime,":")
            elaspedtime = string.atof(t[0]) * 3600 + string.atof(t[1]) * 60 + string.atof(t[2])
            cpuUsage = (cputime - preCpuTime) * 1.0/ (elaspedtime - preElaspedTime) * 100.0
            return (cpuUsage, curVM, cputime, elaspedtime)
    return None

def networkWork(filename, nothing):
    filter = "\"ip and not http and not (tcp port srcport and ip host srchost and tcp port dstport and ip host dsthost)\""
    if sys.platform.find("win")>=0:
#        file = os.popen("ps aux -W")
#        lines = file.readlines()
#        for line in lines:
#            if line.find("C:\\\"Program Files\"\\Wireshark\\tshark") >=0:
#                return 
#        os.system("tshark -i 3 -f ip -q -w " + filename)
        cmd = "tshark -i 3 -f \"tcp port 3979\" -q -w " + filename;
        os.system(cmd + "&");
#        os.system("C:\\\"Program Files\"\\Wireshark\\tshark -i 3 -f ip -q -w " + filename)
    else:
#        file = os.popen("ps aux|grep tshak")
#        lines = file.readlines()
#        if(len(lines) >=2):
#            print "return", len(lines)
#            return 
        if(Configuration.getHostName()).find("siqi")>=0:
#            tshark = "nohup tshark -f \"not (port 80 or port 25 or port 21 or port 22 or port 137 or port 67 or port 53 or dst 255.255.255.255) and not arp and not icmp and ip\" "
            tshark = "nohup tshark -f \"tcp port 3979\" ";
            cmd = tshark + "-q -w " + filename + "& "
#            cmd = "ssh -i /home/siqi/das3/id_dsa root@localhost '" + tshark + " -q -w " + filename + " &'&"
#            file = open("/home/siqi/t.sh","w")
#            print >> file, cmd
#            file.flush()
#            file.close()
##            os.system("chmod a+x ~/t.sh")
#            time.sleep(2)
            os.system(cmd)
    
    print "measureNetwork ..."
    return filename

def measureNetwork(filename):
#    t = threading.Thread(None, networkWork)
#    t.start()
    thread.start_new_thread(networkWork, (filename, 0))
#    thread.start_new_thread(measurePort)

if __name__ == "__main__":
    ret = (0,0,0,0)
    if sys.platform == "win32":
        ret = pslist(preCpuTime, preElaspedTime)
        preCpuTime = ret[2]
        preElaspedTime = ret[3]
    print ret
#    psutilMeasure(0)
#    if sys.platform == "win32":
#        import psutil
#        for x in range(5): 
#            print psutil.cpu_percent(interval=1) 
#  abc = Performance()
#  print "starting"
#  abc.start()
#  print "started"
#  print abc.networkFileName
#    preCpuTime = 0.0
#    preElaspedTime = 0.0
#    while True:
#        if sys.platform == "win32":
#            f1 = os.popen("pslist -m openttd")
#            lines = f1.readlines()
##            print string.split(lines[3])[2]
#            curVM = string.atof(string.split(lines[3])[2])
#            f2 = os.popen("pslist openttd")
#            lines = f2.readlines()
#            words = string.split(lines[3])
#            scputime = words[6]
#            selaspedtime = words[7]
##            print scputime, selaspedtime
#            t = string.split(scputime,":")
#            cputime = string.atof(t[0]) * 3600 + string.atof(t[1]) * 60 + string.atof(t[2])
#            t = string.split(selaspedtime,":")
#            elaspedtime = string.atof(t[0]) * 3600 + string.atof(t[1]) * 60 + string.atof(t[2])
#            cpuUsage = (cputime - preCpuTime) / (elaspedtime - preElaspedTime) * 100
#            preCpuTime = cputime
#            preElaspedTime = elaspedtime
#            print (cpuUsage, curVM)
##            return (cpuUsage, curVM)
#    while True:
#        for process in psutil.get_process_list():
#            if process.name.find("openttd") >=0:
#                print process.name
#                print "win32", process.get_cpu_percent(), process.get_cpu_times(), process.get_memory_percent()
#        time.sleep(0.5)